import { Engine } from '@designable/core'
import {
  transformToSchema,
  transformToTreeNode,
} from '@designable/formily-transformer'
import { message } from 'antd'
import {
  request,
  getUrlParam,
  sourceRequest,
  getUserType,
} from '@designable/event-system'
import moment from 'moment'
import { savePageData } from './api'

let cacheSchema = null
let cachePageList = null
let cacheDesigner = null
const applicationCode = 'admin-schema'

export function pageLabelEdit(params: object) {
  return request({
    uri: '/api/platform/pageLabel/edit',
    method: 'POST',
    params: {
      applicationCode: applicationCode,
      applicationName: '中台schema',
      labelStatus: 'enable',
      language: null,
      ...params,
    },
  })
}

function platformUploadImage(params: Blob) {
  const formData = new FormData()
  formData.append('image', params)
  return request({
    uri: '/api/platform/upload/image',
    params: formData,
    method: 'POST',
  })
}

function pageLabelGet(params: { applicationCode: string }) {
  const userType = getUserType()
  return request({
    uri:
      userType === 'tenant'
        ? '/api/tenant/pageLabel/get'
        : '/api/platform/pageLabel/get',
    method: 'POST',
    params,
  })
}

const onUpload = async (data: any, name: string) => {
  const jsonData = JSON.stringify(data, null, 4)
  const blob = new Blob([jsonData], {
    type: 'application/json',
  })
  const file = new File([blob], `${name}.json`)
  const res: any = await platformUploadImage(file)
  return {
    pageName: name,
    fileUrl: res.fileUrl,
    updateTime: moment().format('YYYY-MM-DD HH:mm:ss'),
  }
}

export const saveSchema = async (designer: Engine) => {
  let pageName = getUrlParam('page')
  const schema = transformToSchema(designer.getCurrentTree())

  if (!pageName) {
    message.error('请先选择页面')
    return
  }
  localStorage.setItem('formily-schema', JSON.stringify(schema))

  const pageContent = await onUpload(schema, pageName)
  const res: any = await pageLabelGet({ applicationCode: applicationCode })
  const content = JSON.parse(res.content || '[]')
  const existsIndex = content.findIndex(
    (item: any) => item.pageName === pageName
  )
  if (existsIndex > -1) {
    savePageData({
      title: 'test',
      route: pageName,
    })
    content[existsIndex] = {
      ...content[existsIndex],
      fileUrl: pageContent.fileUrl,
      updateTime: pageContent.updateTime,
    }
  } else {
    content.push(pageContent)
  }
  res.content = JSON.stringify(content)
  await pageLabelEdit(res)
  message.success('保存成功')
}

export const getSchema = async (pageNameParam?: string) => {
  let pageName = getUrlParam('page') || pageNameParam
  // if (!pageNameParam && cacheSchema) return cacheSchema

  if (!pageName) {
    message.error('请先选择页面')
    return JSON.parse(localStorage.getItem('formily-schema') || '{}')
  }
  try {
    let pageList = cachePageList
    if (!cachePageList) {
      const res: any = await pageLabelGet({ applicationCode: applicationCode })
      pageList = JSON.parse(res.content || '[]')
      cachePageList = pageList
    }

    // 首先尝试精确匹配
    let page = pageList.find((item: any) => item.pageName === pageName)

    // 如果精确匹配失败，尝试动态通配符匹配
    if (!page) {
      // 将末尾部分替换为*号进行匹配
      const pathParts = pageName.split('/')

      if (pathParts.length > 1) {
        // 将最后一个非空部分替换为*
        pathParts[pathParts.length - 1] = '*'
        const wildcardPath = pathParts.join('/')

        page = pageList.find((item: any) => item.pageName === wildcardPath)
      }
    }

    if (!page) {
      return {}
    }
    const schema = await sourceRequest.get(page.fileUrl)
    cacheSchema = schema
    return schema || {}
  } catch (error) {
    console.log('getSchema error', error)
    return JSON.parse(localStorage.getItem('formily-schema') || '{}')
  }
}

export const loadInitialSchema = async (designer?: Engine) => {
  const schema = await getSchema()
  try {
    if (cacheDesigner) {
      cacheDesigner.setCurrentTree(transformToTreeNode(schema))
      return
    }
    if (!designer) return
    cacheDesigner = designer
    designer.setCurrentTree(transformToTreeNode(schema))
  } catch {}
}

export const getPageList = async () => {
  const res: any = await pageLabelGet({ applicationCode: applicationCode })
  const content = JSON.parse(res.content || '[]')
  return Promise.resolve(content)
}

export const savePageList = async (pageList: any) => {
  await pageLabelEdit({
    content: JSON.stringify(pageList),
  })
}
